package com.wodsy.phoenix.dataservice.userc.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.wodsy.phoenix.commons.utils.RandomUtils;
import com.wodsy.phoenix.commons.utils.RegexUtils;
import com.wodsy.phoenix.commons.utils.sms.SMSSenderUtil;
import com.wodsy.phoenix.datadao.base.IBaseDao;
import com.wodsy.phoenix.datadao.userc.dao.MobileCaptchaDao;
import com.wodsy.phoenix.datadao.userc.dao.UserManagementDao;
import com.wodsy.phoenix.dataobject.base.PhoenixResponseWrapper;
import com.wodsy.phoenix.dataobject.base.ResponseCodeConstants;
import com.wodsy.phoenix.dataobject.userc.constants.UserConstants;
import com.wodsy.phoenix.dataobject.userc.model.MobileCaptcha;
import com.wodsy.phoenix.dataobject.userc.model.UserBasic;
import com.wodsy.phoenix.dataobject.userc.vo.UserBasic4EmailRegister;
import com.wodsy.phoenix.dataobject.userc.vo.UserBasic4Login;
import com.wodsy.phoenix.dataobject.userc.vo.UserBasic4PhoneRegister;
import com.wodsy.phoenix.dataservice.base.AbstractBaseService;
import com.wodsy.phoenix.dataservice.userc.service.UserManagementService;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.*;
import java.sql.Timestamp;
import java.util.Date;


@Service(interfaceName="com.wodsy.phoenix.dataservice.userc.service.UserManagementService" )
public class UserManagementServiceImpl  extends AbstractBaseService<UserBasic, Integer> implements UserManagementService {
	
	@Autowired
    private JmsTemplate jmsTemplate;   
	@Autowired
    private Topic topic;



	@Autowired
	private UserManagementDao userManagementDao;

	@Autowired
	private MobileCaptchaDao mobileCaptchaDao;


	@Override
	protected IBaseDao<UserBasic, Integer> getIBaseDao() {
		return userManagementDao;
	}

	@Transactional(value="xa")
	public PhoenixResponseWrapper<UserBasic4EmailRegister> registerByEmail(UserBasic4EmailRegister userBasic4Register) {

		//查询两次密码是否一致
		PhoenixResponseWrapper<UserBasic4EmailRegister>  response= new PhoenixResponseWrapper<UserBasic4EmailRegister>();
		if(!userBasic4Register.getUserPwd().equals(userBasic4Register.getUserPwdConfirm())){
			response.setCode(ResponseCodeConstants.PASSWORD_NOT_CONSISTENT);
			response.setMsg("两次输入的密码不一致");
			return response;
		}

		//查询账号，手机号，或者邮箱是否注册
		String email = userBasic4Register.getUserEmail();
		if(email!=null && !email.equals("")){
			//判断邮箱是否合法
			boolean  isEmail = RegexUtils.isEmailFormat(email);
			if(!isEmail){
				response.setCode(ResponseCodeConstants.EMAIL_FORMAT_NOT_VALID);
				response.setMsg("邮箱格式错误");
				return response;
			}

			//查询邮箱是否注册

			UserBasic userBasic= new UserBasic(	);
			userBasic = userManagementDao.findByEmail(email);
			if(userBasic!=null){
				response.setCode(ResponseCodeConstants.EMAIL_IS_REGISTERED);
				response.setMsg("邮箱已经注册");
				return response;
			}
		}



		String userAccount =userBasic4Register.getUserAccount();
		if(userAccount!=null ){
			//判断账户是否合法
			boolean isAccount = RegexUtils.isAccountFormat(userAccount);
			if(!isAccount){
				response.setCode(ResponseCodeConstants.ACCOUNT_FORMAT_NOT_VALID);
				response.setMsg("账户格式错误");
				return response;
			}
			//查询账号是否注册
			UserBasic userBasic= new UserBasic(	);
			userBasic = userManagementDao.findByAccount(userAccount);
			if(userBasic!=null){
				response.setCode(ResponseCodeConstants.ACCOUNT_IS_REGISTERED);
				response.setMsg("账号已经注册");
				return response;
			}

		}

		//保存用户
        try{
			UserBasic userBasic= new UserBasic(	);
			BeanUtils.copyProperties(userBasic4Register,userBasic );

			userManagementDao.save(userBasic);


		}catch (Exception e	){
			response.setCode(ResponseCodeConstants.SAVE_USER_FAIL);
			response.setMsg("保存用户失败");
			return response;
		}

		response.setCode(ResponseCodeConstants.SUCCESS);
		response.setMsg("保存成功");
		return response;
	}

	/**
	 * 用户注册（手机）
	 * @param userBasic4PhoneRegister
	 * @return
	 */
	@Transactional(value="xa")
	public PhoenixResponseWrapper<UserBasic4EmailRegister> registerByMobile(UserBasic4PhoneRegister userBasic4PhoneRegister) {
		//查询两次密码是否一致
		PhoenixResponseWrapper<UserBasic4EmailRegister>  response= new PhoenixResponseWrapper<UserBasic4EmailRegister>();
		if(!userBasic4PhoneRegister.getUserPwd().equals(userBasic4PhoneRegister.getUserPwdConfirm())){
			response.setCode(ResponseCodeConstants.PASSWORD_NOT_CONSISTENT);
			response.setMsg("两次输入的密码不一致");
			return response;
		}

		//查询账号，手机号，或者邮箱是否注册
		Long phone = userBasic4PhoneRegister.getUserTel();
		if(phone!=null && phone.intValue()!=0){
			//判断手机是否合法
			boolean isPhone = RegexUtils.isPhoneFormat(phone.toString());
			if(!isPhone){
				response.setCode(ResponseCodeConstants.PHONE_FORMAT_NOT_VALID);
				response.setMsg("手机格式错误");
				return response;
			}

			//查询手机号是否注册
			UserBasic userBasic= new UserBasic(	);
			userBasic = userManagementDao.findByPhone(phone);
			if(userBasic!=null){
				response.setCode(ResponseCodeConstants.PHONE_IS_REGISTERED);
				response.setMsg("手机号已经注册");
				return response;
			}

			//查询手机对应的验证码是否正确
			MobileCaptcha mobileCaptcha = mobileCaptchaDao.getByMobile(phone);
			if(mobileCaptcha==null ||  !mobileCaptcha.getCaptcha().equals(userBasic4PhoneRegister.getMobileCaptha())){
				response.setCode(ResponseCodeConstants.CAPTCHA_IS_VALID);
				response.setMsg("验证码不存在或已失效");
				return response;
			}
		}



		String userAccount =userBasic4PhoneRegister.getUserAccount();
		if(userAccount!=null ){
			//判断账户是否合法
			boolean isAccount = RegexUtils.isAccountFormat(userAccount);
			if(!isAccount){
				response.setCode(ResponseCodeConstants.ACCOUNT_FORMAT_NOT_VALID);
				response.setMsg("账户格式错误");
				return response;
			}
			//查询账号是否注册
			UserBasic userBasic= new UserBasic(	);
			userBasic = userManagementDao.findByAccount(userAccount);
			if(userBasic!=null){
				response.setCode(ResponseCodeConstants.ACCOUNT_IS_REGISTERED);
				response.setMsg("账号已经注册");
				return response;
			}

		}



		//保存用户
		try{
			UserBasic userBasic= new UserBasic(	);
			BeanUtils.copyProperties(userBasic4PhoneRegister,userBasic );

			userManagementDao.save(userBasic);


		}catch (Exception e	){
			response.setCode(ResponseCodeConstants.SAVE_USER_FAIL);
			response.setMsg("保存用户失败");
			return response;
		}

		response.setCode(ResponseCodeConstants.SUCCESS);
		response.setMsg("保存成功");
		return response;
	}

	/**
	 * 登录查找
	 * @param user 用户信息
	 * @return
	 */
	@Transactional(value="xa")
	public PhoenixResponseWrapper<UserBasic> login(UserBasic4Login user) {
		PhoenixResponseWrapper<UserBasic> result = new PhoenixResponseWrapper<>();
		String unionId  = user.getUnionId();
		String password  = user.getUserPwd();
		UserBasic ub = null;

		//判断unionId为 邮件、用户账号、还是手机号

		boolean  isEmail = RegexUtils.isEmailFormat(unionId);
		if(isEmail) {
			ub= userManagementDao.findByEmail(unionId);

		}
		boolean isPhone = RegexUtils.isPhoneFormat(unionId);
		if(isPhone){
			ub= userManagementDao.findByPhone(Integer.parseInt(unionId));
		}

		boolean isAccount = RegexUtils.isAccountFormat(unionId);
		if(isAccount){
			ub= userManagementDao.findByAccount(unionId);
		}

		if(ub!=null){
			if(ub.getUserPwd().equals(password) ){
				if( ub.getUserStatus()==UserConstants.ACTIVATED){
					result.setCode(ResponseCodeConstants.SUCCESS);
					result.setMsg("成功");
					result.setObj(ub);
					return result;
				}else{
					result.setCode(ResponseCodeConstants.USER_NOT_ACTIVATED);
					result.setMsg("用户未激活");
					return result;
				}
			}else{
				result.setCode(ResponseCodeConstants.PASSWORD_IS_WRONG);
				result.setMsg("密码错误");
				return result;
			}

		}
		result.setCode(ResponseCodeConstants.USER_NOT_EXIST);
		result.setMsg("用户不存在");
		result.setObj(ub);
		return result;

	}

	@Override
	@Transactional(value="xa")
	public PhoenixResponseWrapper<UserBasic> activiteByEmail(String email) {
		PhoenixResponseWrapper<UserBasic> result = new PhoenixResponseWrapper<>();
		UserBasic ub = userManagementDao.findByEmail(email);
		if (ub != null) {
			ub.setUserStatus(UserConstants.ACTIVATED);
			ub.setUpdateDatetime(new Date(System.currentTimeMillis()));
			userManagementDao.update(ub);
			result.setCode(ResponseCodeConstants.SUCCESS);
			result.setMsg("激活成功");
			result.setObj(ub);
			return result;
		}
		result.setCode(ResponseCodeConstants.USER_NOT_EXIST);
		result.setMsg("用户不存在");
		return result;
	}

	/**
	 * 发送验证码
	 * @param mobile
	 * @return
	 */
	@Transactional(value="xa")
	public PhoenixResponseWrapper<MobileCaptcha> sendMobileMsg(long mobile){


		PhoenixResponseWrapper<MobileCaptcha> result = null;
		MobileCaptcha mobileCaptcha = new MobileCaptcha();
		try {
			String captch = RandomUtils.generateNumberStr(6);
			String content ="【我的手艺网-布作】"+captch+"]（验证码）,请勿向任何人泄露。";
			SMSSenderUtil.sendCaptcha(String.valueOf(mobile),content);


			result = new PhoenixResponseWrapper<>();

			mobileCaptcha.setCaptcha(captch);
			mobileCaptcha.setCreateTime(new Timestamp(System.currentTimeMillis()));
			mobileCaptcha.setMobile(mobile);
			mobileCaptchaDao.save(mobileCaptcha);
			result.setCode(ResponseCodeConstants.SUCCESS);
			result.setMsg("获取成功");
			result.setObj(mobileCaptcha);
		} catch (Exception e) {
			result.setCode(ResponseCodeConstants.SEND_MOBILE_CAPTCHA_FAIL);
			result.setMsg("发送信息失败");

		}


		return result;
	}

	private boolean sendTopic() {
        try {   
	        	JSONObject jsonObject = new JSONObject();  
	            jsonObject.put("username", "lwc");  
	            jsonObject.put("password", "123");  
	            
	            
                final String msgJson = jsonObject.toString(); 
                logger.info("start to send topic to " + topic.getTopicName()   
                        + ", message : " + msgJson);   
                jmsTemplate.send(topic, new MessageCreator(){   
  
                    @Override  
                    public Message createMessage(Session session)   
                            throws JMSException {   
                        TextMessage message = session   
                                .createTextMessage(msgJson);   
                        return message;   
                    }   
                });   
            return true;   
        } catch (Exception e) {

			logger.error("Error: send topic failure:" + e.getMessage(), e);
            return false;   
        }   
    }   
	
	/**
	 * 修改密码
	 * @param user
	 */
	@Transactional(rollbackFor=Exception.class)
	public void changePass(UserBasic user) {
		UserBasic user4Modify = userManagementDao.get(user.getId());
		user4Modify.setUserPwd(user.getUserPwd());
		userManagementDao.update(user4Modify);
	}
	
	/**
	 * 校验密码
	 * @param user
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean checkPass(String pass,UserBasic user) {
		UserBasic userFromDatabase = userManagementDao.get(user.getId());
		if(userFromDatabase.getUserPwd().equals(pass)){
			return true;
		}
		return false;
	}
	
	/**
	 * 删除账户
	 * @param userids
	 */
	@Transactional(rollbackFor=Exception.class)
	public void delUser(String userids) {
		String[] ids = userids.split(",");
		for (int i = 0; i < ids.length; i++) {
			UserBasic user = userManagementDao.get(Integer.parseInt(ids[i]));
			userManagementDao.delete(user);
		}
	}

	
	public static void main(String[] args) {
		com.alibaba.dubbo.container.Main.main(args);
	}

}
